package com.comet.config;

import org.apache.shardingsphere.api.sharding.standard.PreciseShardingAlgorithm;
import org.apache.shardingsphere.api.sharding.standard.PreciseShardingValue;
import java.math.BigInteger;
import java.util.Collection;

/**
 * 标准分表策略Precise
 */
public class TablePreciseShardingAlgorithm implements PreciseShardingAlgorithm {

    @Override
    public String doSharding(Collection collection, PreciseShardingValue preciseShardingValue) {

        // select * from order order_id = '' or order_id in ('','')

        // 逻辑表名
        String logicTableName = preciseShardingValue.getLogicTableName();
        // 分片键
        String shardingKey = preciseShardingValue.getColumnName();
        // 分片键的值
        Long shardingKeyValue = (Long) preciseShardingValue.getValue();
        // 转换成BigInteger进行取模操作
        BigInteger shardingKeyValueB = BigInteger.valueOf(shardingKeyValue);
        // 分片策略：course_$->{shardingKey%2+1}
        BigInteger tableNum = shardingKeyValueB.mod(new BigInteger("2")).add(new BigInteger("1"));
        // 最终分片策略：course_$->{shardingKey%2+1}
        String tableShardingStrategy = logicTableName + "_" + tableNum;
        if (collection.contains(tableShardingStrategy)) {
            return tableShardingStrategy;
        }
        throw new UnsupportedOperationException("router:" + tableShardingStrategy + " is not supported, please check your config");
    }
}
